package com.yuyu.qingmangmall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.mysql.cj.util.StringUtils;
import com.yuyu.common.to.es.SkuEsModel;
import com.yuyu.qingmangmall.search.config.QingmangElasticsSarchConfig;
import com.yuyu.qingmangmall.search.constant.EsConstant;
import com.yuyu.qingmangmall.search.service.MallSearchService;
import com.yuyu.qingmangmall.search.vo.SearchParam;
import com.yuyu.qingmangmall.search.vo.SearchResult;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class MallSearchServiceImpl implements MallSearchService {

    @Autowired
    RestHighLevelClient restHighLevelClient;

    // 去es进行检索
    @Override
    public SearchResult search(SearchParam param) {
        // 动态构建出查询需要的DSL语句

        SearchResult searchResult = null;
        // 1.准备检索请求
        SearchRequest searchRequest =  builderSearchRequest(param);

        try {
            // 2.执行检索请求
            SearchResponse response = restHighLevelClient.search(searchRequest, QingmangElasticsSarchConfig.COMMON_OPTIONS);

            // 3.分析响应数据封装成我们需要的格式
            searchResult = builderSearchResult(response,param);
        } catch (IOException e) {
            e.printStackTrace();
        }


        return searchResult;
    }


    /**
     * 准备检索请求
     * 模糊匹配，过滤（按照属性，分类，品牌，价格区间，库存），排序，分页，高亮，聚合分析
     * @return
     */
    private SearchRequest builderSearchRequest(SearchParam param) {
        SearchSourceBuilder source = new SearchSourceBuilder();

        /*
            模糊匹配，过滤（按照属性，分类，品牌，价格区间，库存）
         */
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        // 1.1 must-模糊匹配
        if (!StringUtils.isNullOrEmpty(param.getKeyword())){
            boolQuery.must(QueryBuilders.matchQuery("skuTitle",param.getKeyword()));
        }
        // 1.2 bool - filter - 过滤 按照分类
        if (param.getCatalog3Id()!=null){
            boolQuery.filter(QueryBuilders.termQuery("catalogId", param.getCatalog3Id()));
        }

        // 1.2 bool - filter  过滤 按照品牌
        if (param.getBrandId()!=null&&param.getBrandId().size()>0){
            boolQuery.filter(QueryBuilders.termsQuery("brandId",param.getBrandId()));
        }

        // 1.2 bool - filter 过滤 按照属性 attrs=1_3G:4G&attrs=2_骁龙855:骁龙845
        if (param.getAttrs()!=null&&param.getAttrs().size()>0) {
            for (String attr : param.getAttrs()) {
                // attrs=1_3G:4G
                BoolQueryBuilder nestedBoolQuery = QueryBuilders.boolQuery();

                String[] s = attr.split("_"); // s[0] 检索属性的id
                String[] strings = s[1].split(":"); // 3G:4G

                nestedBoolQuery.must(QueryBuilders.termQuery("attrs.attrId", s[0]));
                nestedBoolQuery.must(QueryBuilders.termsQuery("attrs.attrValue", strings));

                // 每一个必须都得生成一个nested查询
                NestedQueryBuilder attrsNested = QueryBuilders.nestedQuery("attrs", nestedBoolQuery, ScoreMode.None);
                boolQuery.filter(attrsNested);
            }

        }
        // 1.2 bool - filter 过滤 按照库存
        if (param.getHasStock()!=null){
            boolQuery.filter(QueryBuilders.termsQuery("hasStock",param.getHasStock()==1));
        }

        // 1.2 bool - filter 过滤 按照价格区间  skuPrice=1_500/_500/500_
        if (!StringUtils.isNullOrEmpty(param.getSkuPrice())){
            String skuPrice = param.getSkuPrice();
            String[] s = skuPrice.split("_");
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("skuPrice");
            if (s.length==2){
                // 1_500 和  _500的剪切数组的结果长度都是2
                if (StringUtils.isNullOrEmpty(s[0])){
                    // _500
//                    rangeQuery.gte(0);
                    rangeQuery.lte(s[1]);
                }else {
                    // 1_500
                    rangeQuery.gte(s[0]);
                    rangeQuery.lte(s[1]);
                }
            }else if (s.length==1){
                // 500_
                rangeQuery.gte(s[0]);
            }
            boolQuery.filter(rangeQuery);
        }
        source.query(boolQuery);

        /*
            排序，分页，高亮
         */

        // 2.1 排序 sort=hotScore_asc/desc
        if (!StringUtils.isNullOrEmpty(param.getSort())) {
            String[] s = param.getSort().split("_");

            SortOrder sortOrder = s[1].equalsIgnoreCase("asc")?SortOrder.ASC:SortOrder.DESC;
            source.sort(s[0],sortOrder);
        }

        // 2.2 分页
        // pageNum=1 from=0 size=5 1-5
        // pageNum=2 from=5 size=5 6-10
        // from=(pageNum-1)*size
        Integer pageNum = param.getPageNum();
        source.from((pageNum-1)*EsConstant.PRODUCT_PAGE_SIZE);
        source.size(EsConstant.PRODUCT_PAGE_SIZE);

        // 2.3 高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("skuTitle");
        highlightBuilder.preTags("<b style='color: red'>");
        highlightBuilder.postTags("</b>");
        source.highlighter(highlightBuilder);
        /*
            聚合分析 品牌 分类 属性
         */
        // 1.品牌聚合
        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg");
        brand_agg.field("brandId").size(50);
        // brand_agg 子聚合
        brand_agg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1));
        brand_agg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));

        source.aggregation(brand_agg);

        // 2.分类聚合
        TermsAggregationBuilder catalog_agg = AggregationBuilders.terms("catalog_agg");
        catalog_agg.field("catalogId").size(50);
        // catalog_agg 子聚合
        catalog_agg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(1));

        source.aggregation(catalog_agg);

        // 3.属性聚合 嵌套聚合
        NestedAggregationBuilder nestedAttrs_agg = AggregationBuilders.nested("attrs_agg", "attrs");
        // 聚合出当前所有的attrId
        TermsAggregationBuilder attr_id_agg = AggregationBuilders.terms("attr_id_agg");
        attr_id_agg.field("attrs.attrId").size(50);
        // attr_id_agg 子聚合  一个属性id对应一个属性名，对应多个属性值
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1));
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_value_Agg").field("attrs.attrValue").size(50));
        // 子聚合 attr_id_agg
        nestedAttrs_agg.subAggregation(attr_id_agg);
        source.aggregation(nestedAttrs_agg);

        System.out.println("构建的DSL："+source.toString());
        SearchRequest searchRequest = new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, source);

        return searchRequest;
    }

    /**
     * 分析响应数据封装成我们需要的格式
     * @param response
     * @return
     */
    private SearchResult builderSearchResult(SearchResponse response, SearchParam param) {

        SearchResult searchResult = new SearchResult();
        SearchHits hits = response.getHits();
        // 1.返回的所有查询到的商品
        List<SkuEsModel> skuEsModels = new ArrayList<>();
        if (hits.getHits()!=null&&hits.getHits().length > 0) {
            for (SearchHit hit : hits.getHits()) {
                // SkuEsModel skuEsModel = new SkuEsModel();
                String sourceAsString = hit.getSourceAsString();
                SkuEsModel skuEsModel = JSON.parseObject(sourceAsString, SkuEsModel.class);
                if (!StringUtils.isNullOrEmpty(param.getKeyword())){
                    HighlightField skuTitle = hit.getHighlightFields().get("skuTitle");
                    String string = skuTitle.getFragments()[0].string();
                    skuEsModel.setSkuTitle(string);
                }

                skuEsModels.add(skuEsModel);
            }
        }

        searchResult.setProducts(skuEsModels);
        // 2.当前所有商品涉及到的所有属性信息
        ParsedNested attrs_agg = response.getAggregations().get("attrs_agg");
        ParsedLongTerms attr_id_agg = attrs_agg.getAggregations().get("attr_id_agg");
        List<SearchResult.AttrVo> attrVos = new ArrayList<>();
        for (Terms.Bucket bucket : attr_id_agg.getBuckets()) {
            SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
            long attrId = bucket.getKeyAsNumber().longValue(); // 属性Id
            ParsedStringTerms attr_name_agg = bucket.getAggregations().get("attr_name_agg");
            String attrName = attr_name_agg.getBuckets().get(0).getKeyAsString();
            ParsedStringTerms attr_value_Agg = bucket.getAggregations().get("attr_value_Agg");
            List<String> attrValues = new ArrayList<>();
            for (Terms.Bucket attr_value_bucket : attr_value_Agg.getBuckets()) {
                String attr_value = attr_value_bucket.getKeyAsString();
                attrValues.add(attr_value);
            }
            attrVo.setAttrId(attrId);
            attrVo.setAttrName(attrName);
            attrVo.setAttrValue(attrValues);
            attrVos.add(attrVo);
        }
        searchResult.setAttrs(attrVos);

        // 3.当前所有商品涉及到的所有品牌信息
        ParsedLongTerms brand_agg = response.getAggregations().get("brand_agg");
        List<SearchResult.BrandVo> brandVos = new ArrayList<>();
        for (Terms.Bucket brandBucket : brand_agg.getBuckets()) {
            SearchResult.BrandVo brandVo = new SearchResult.BrandVo();
            long brandId = brandBucket.getKeyAsNumber().longValue(); // 品牌Id
            // 拿到brand_agg的子聚合  brand_img_agg
            ParsedStringTerms brand_img_agg = brandBucket.getAggregations().get("brand_img_agg");
            // 每个品牌只有一个品牌图片，所以子聚合的集合只有一个元素
            Terms.Bucket bucket = brand_img_agg.getBuckets().get(0);
            String brandImg = bucket.getKey().toString();
            // 拿到brand_agg的子聚合  brand_name_agg
            ParsedStringTerms brand_name_agg = brandBucket.getAggregations().get("brand_name_agg");
            // 每个品牌只有一个名字，所以子聚合的集合只有一个元素
            String brandName = brand_name_agg.getBuckets().get(0).getKey().toString();

            brandVo.setBrandId(brandId);
            brandVo.setBrandImg(brandImg);
            brandVo.setBrandName(brandName);
            brandVos.add(brandVo);
        }
        searchResult.setBrands(brandVos);
        // 4.当前所有商品涉及到的所有分类信息
        ParsedLongTerms catalog_agg = response.getAggregations().get("catalog_agg");
        List<SearchResult.CatalogVo> catalogVos  = new ArrayList<>();
        for (Terms.Bucket catalogBucket : catalog_agg.getBuckets()) {
            SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();
            Long catalogId = (Long) catalogBucket.getKey(); // 分类id
            // 拿到catalog_agg的子聚合
            ParsedStringTerms catalog_name_agg = catalogBucket.getAggregations().get("catalog_name_agg");
            //每个分类只有一个名字，所以子聚合的集合只有一个元素
            String catalogName = catalog_name_agg.getBuckets().get(0).getKey().toString();
            catalogVo.setCatalogId(catalogId);
            catalogVo.setCatalogName(catalogName);
            catalogVos.add(catalogVo);
        }
        searchResult.setCatalogs(catalogVos);


        long value = hits.getTotalHits().value; // 查询的总记录数
        // 5.分页信息-页码
        searchResult.setPageNum(param.getPageNum());
        // 6.分页信息-总记录数
        searchResult.setTotal(value);
        // 7.分页信息-总页码
        long totalPages = (value%EsConstant.PRODUCT_PAGE_SIZE)==0?value/EsConstant.PRODUCT_PAGE_SIZE:(value/EsConstant.PRODUCT_PAGE_SIZE)+1;
        searchResult.setTotalPages((int)totalPages);
        // 8.分页信息页码集合
        List<Integer> pageNavs = new ArrayList<>();
        for (int i=1;i<=totalPages;i++){
            pageNavs.add(i);
        }
        searchResult.setPageNavs(pageNavs);

        return searchResult;
    }
}
